package cc.luoqiming.upload.controller;

import cc.luoqiming.upload.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {


    @Value("${web.upload.path}")
    private String uploadPath;

    @GetMapping("/uploadView")
    public String uploadView() {
        return "/index";
    }

    @PostMapping(value = "/saveUpload")
    public String saveUpload(@RequestParam("file") MultipartFile file, Model model) throws IOException {
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            int suffixIndex = fileName.indexOf(".");
            String suffix = file.getOriginalFilename().substring(suffixIndex);
            String uuId = UUID.randomUUID().toString();
            String img = uploadPath + uuId  + suffix;
            //String imgStr = "static/pics/" + uuId  + suffix;
            File newFile = new File(img);
            file.transferTo(newFile);
            model.addAttribute("imgsrc", "/"+ uuId + suffix);
        }

        model.addAttribute("result","上传成功");
        return "result";
    }

    @GetMapping("/cutImage")
    public String cutImage(int x, int y, int width, int height, String fileName, Model model) {
        ImageUtil imageUtil = new ImageUtil();

        try {
            File imgSrc = new File(uploadPath + fileName);

            String cutFileName = "cut_" + System.currentTimeMillis() + "_" + imgSrc.getName();
            File cutSrc = new File(uploadPath + cutFileName);
            OutputStream outputStream = new FileOutputStream(cutSrc);


            imageUtil.cutImage(imgSrc, outputStream, x, y, width, height);
            model.addAttribute("cutImage", cutFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return "cutImage";
    }
}
